第26章 模块

CommonJS 模块定义需要使用 require() 指定依赖,而使用 exports 对象定义自己的公共 API

var moduleB = require('./moduleB');
module.exports = {
  stuff: moduleB.doStuff();
}

无论一个模块在 require()中被引用多少次,模块永远是单例

console.log('moduleA');
var a1 = require('./moduleA');
var a2 = require('./moduleA');
console.log(a1 === a2); // true

模块的一个主要用途是托管类定义

class A {}
module.exports = A;
var A = require('./moduleA');
var a = new A();
// 也可以将类实例作为导出值
module.exports = new A();

ES6 模块是作为一整块 JavaScript 代码而存在的。带有 type="module" 属性的